package com.ckjava.test.web.base;

import com.ckjava.test.entity.base.BaseMybatisEntity;
import com.ckjava.test.service.base.BaseMybatisCrudService;
import com.ckjava.xutils.Constants;
import com.ckjava.xutils.http.HttpResponse;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Api
public abstract class BaseCrudController<S extends BaseMybatisCrudService, E extends BaseMybatisEntity> extends CorsController implements Constants {

    @Autowired
    public S service;

    @ApiOperation("根据 id 获取一个对象")
    @GetMapping("/{id}")
    public HttpResponse<E> get(
            @PathVariable Long id) {
        return HttpResponse.getReturn((E) service.get(id).get(), HTTPCODE.code_200, null);
    }

    @ApiOperation("获取所有的对象")
    @GetMapping(value = "/all")
    public HttpResponse<List<E>> getAll() {
        return HttpResponse.getReturn((List<E>) service.getAll().get(), HTTPCODE.code_200, null);
    }

    @ApiOperation("保存或者修改一个对象")
    @PostMapping
    public HttpResponse<Long> saveOrUpdate(
            @RequestBody E e) {
        return HttpResponse.getReturn((Long) service.saveOrUpdate(e).get(), HTTPCODE.code_200, null);
    }

    @ApiOperation("根据 id 删除一个对象")
    @DeleteMapping("/{id}")
    public HttpResponse delete(
            @PathVariable Long id) {
        service.delete(id);
        return HttpResponse.getReturn(null, HTTPCODE.code_200, null);
    }
}
